﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using RH.Common.Extensions;
using RH.Domain;
using RH.Web.ViewModels;
using RH.Web.Utility;
using AutoMapper;

namespace RH.Web.Areas.Private.Controllers
{
    [Authorize(Roles= "Company Admin,Company User")]
    public class CompanyController : BaseController
    {
		private AppEntities _Context = new AppEntities();
        
		#region Constructors
		public CompanyController()
		{
		}

		public CompanyController(UserViewModel currentUser)
			: base(currentUser)
        {
        }
		#endregion Constructors

		#region Action Methods
        public ActionResult Index()
        {
            return View();
        }
		/// <summary>
        /// Company ProfileEdit GET Request Handler
        /// Gets a Company from Database to edit
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
		public ActionResult ProfileEdit()
        {
            EntityRepository repository = new EntityRepository(_Context);
            Company entity = repository.GetCompanyByID(LoggedInUser.Company.ID);

            //if (entity.Address == "__UnKnown")
            //    entity.Address = "";

            //if (entity.Phone == "__UnKnown")
            //    entity.Phone = "";
            
            CompanyViewModel viewModel = Mapper.Map<Company, CompanyViewModel>(entity);


            if (viewModel == null)
            {
                viewModel = new CompanyViewModel();
                viewModel.ID = LoggedInUser.Company.ID;
            }
            //else
            //    viewModel.CountryID = entity.District.Country.ID;            

            ViewBag.PageTitle = String.Format("Edit Company Profile {0}", viewModel != null ? "of " + viewModel.Name : String.Empty);
            //ViewBag.IsRegistrationMode = null;
            return View(viewModel);
        }

		/// <summary>
        /// Company ProfileEdit POST Request Handler
        /// Saves Company Information into the Database
        /// </summary>
        /// <param name="viewModel"></param>
        /// <returns></returns>
		[HttpPost]
        public ActionResult ProfileEdit(CompanyViewModel viewModel)
        {
            if (!ModelState.IsValid)
            {
                ViewBag.PageTitle = String.Format("Edit Company Profile {0}", viewModel != null ? "of " + viewModel.Name : String.Empty);
                return View(viewModel);
            }

			Company entity = null; 
			if (viewModel.ID == 0)
            {
                entity = new Company();
                _Context.AddToCompanies(entity);
            }
            else
                entity = _Context.Companies.FirstOrDefault(P => P.ID == viewModel.ID);

            if (_Context.IsDuplicateCompanyName(viewModel.Name, viewModel.ID))
            {
                ViewBag.PageTitle = String.Format("Edit Company Profile {0}", viewModel != null ? "of " + viewModel.Name : String.Empty);
                ModelState.AddModelError("Name", String.Format("Sorry: This Company Name \"{0}\" Already Exists", viewModel.Name));
                return View(viewModel);
            }

            entity = Mapper.Map<CompanyViewModel, Company>(viewModel, entity);
            entity.ModifiedOn = DateTime.Now;
            entity.CompanyUrl = entity.Name.ToSeoUrl();
            ///Following Should be always true. If a Company goes In active then only Admin can do that.
            ///And inactive companie's users cannot login to the system. 
            ///So following line of code should be safe.
            entity.IsActive = true;
            _Context.SaveChanges();
            ///Rebuild the Content and Company Route Cache, and re-map them in the global routing cache            
            MvcApplication.RefreshRoutes(true);

            viewModel.ID = entity.ID;
            ViewBag.ProfileSaved = true;
            ViewBag.PageTitle = String.Format("Edit Company Profile {0}", viewModel != null ? "of " + viewModel.Name : String.Empty);
            return View(viewModel);
            //return RedirectToAction("Index");       
 
        }
        public ActionResult UploadLogo(int id)
        {
            return View();
        }

        public ActionResult RequestCategory(String reqFrom)
        {
            ViewBag.RequestFrom = reqFrom;
            return View();
        }
		#endregion Action Methods
		
		#region Helper Methods

        #endregion			
    }
}
